import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:smart_devices/model/device_location.dart';

class DeviceLocationLogic extends GetxController {
  RxString search = RxString('');

  Rx<TextEditingController> searchController = Rx(TextEditingController());

  RxList<DeviceLocationModel> pageList = RxList([]);

  late Rx<RefreshController> refreshController;

  @override
  void onInit() {
    super.onInit();
    for (var i = 0; i < 10; i++) {
      pageList.add(DeviceLocationModel(name: '位置 ${i + 1}'));
    }
    refreshController = Rx(RefreshController(initialRefresh: false));
  }

  @override
  void onClose() {
    super.onClose();
    searchController.value.dispose();
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.value.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > 15) {
      return refreshController.value.loadNoData();
    }

    /// 添加
    refreshController.value.loadComplete();
    pageList.add(DeviceLocationModel(name: '位置 ${pageList.length + 1}'));
  }

  void onValueChangedAtIndex(int index, bool flag) {
    for (int i = 0; i < pageList.length; i++) {
      pageList[i].checked = index == i ? flag : false;
    }
    pageList.refresh();
    // update();
  }
}
